from fastapi import APIRouter, Depends,HTTPException
from app.db.session import get_db
from app.db.models.user import Group, User, FriendGroup  # 导入Group模型
from sqlalchemy.orm import Session, joinedload
from app.db.models.user import Apply, Friend
from app.utils.security import get_current_user
from loguru import logger
from ..services.expression import get_expressions
from ..schemas.expression import ExpressionResponse

router = APIRouter(tags=["其他功能"])

@router.get("/expression/select", response_model=ExpressionResponse)
async def select_expressions():
    """获取表情包列表接口"""
    return get_expressions()

@router.get("/grouping/friend",summary="获取分组好友列表")
async def get_grouped_friends(
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_user)
):
    """获取分组好友列表（响应格式严格匹配）"""
    try:
        # 获取用户的所有分组
        groups = db.query(FriendGroup).filter(
            FriendGroup.user_id == current_user.id
        ).options(
            joinedload(FriendGroup.group)
        ).all()

        result_data = []

        for group_rel in groups:
            # 获取该分组下的所有好友
            friends = db.query(Friend).filter(
                Friend.friend_group_id == group_rel.id,
                Friend.status == 1  # 只获取正常状态的好友
            ).options(
                joinedload(Friend.friend)
            ).all()

            friends_data = []
            for friend_rel in friends:
                if friend_rel.friend:  # 确保好友用户存在
                    friends_data.append({
                        "id": friend_rel.id,
                        "remark": friend_rel.remark,
                        "userId": friend_rel.friend.id,
                        "nickname": friend_rel.friend.nickname,
                        "avatar": friend_rel.friend.avatar,
                        "sex": friend_rel.friend.sex,
                        "online": 1 if friend_rel.friend.online else 0,
                        "email": friend_rel.friend.email,
                        "lastAt": friend_rel.friend.last_at.strftime(
                            "%Y-%m-%d %H:%M:%S") if friend_rel.friend.last_at else None,
                        "createdAt": friend_rel.friend.created_at.strftime("%Y-%m-%d %H:%M:%S")
                    })

            result_data.append({
                "id": group_rel.group.id,
                "name": group_rel.group.name,
                "fixed": 1 if group_rel.group.is_default else 0,
                "friends": friends_data
            })

        return {
            "code": 0,
            "message": "成功！",
            "data": result_data
        }

    except Exception as e:
        logger.error(f"获取分组好友列表失败: {str(e)}")
        raise HTTPException(500, detail="服务器繁忙，请稍后重试")


@router.get("/grouping/select", summary="获取分组选择列表")
async def get_grouping_select(db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user) ):
    """
    返回格式示例:
    {
        "code": 0,
        "message": "成功！",
        "data": [
            {"id": 509, "name": "我的好友"}
        ]
    }
    """
    logger.debug(f"当前用户token验证结果: {current_user.nickname}")  # 添加日志
    user_groups = db.query(FriendGroup).join(Group).filter(
        FriendGroup.user_id == current_user.id
    ).all()

    # 构建返回数据（使用friend_group.id作为前端需要的分组ID）
    data = [{
        "id": group.id,  # 这里返回的是friend_groups表的ID
        "name": group.group.name
    } for group in user_groups]

    return {
        "code": 0,
        "message": "成功！",
        "data": data
    }
